package com.hp.TrimClient;

import java.io.File;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import com.hp.TrimClient.MainObjects.Record;
import com.hp.TrimClient.MainObjects.TrimObject;

public class HttpEntityConverter {

	private Boolean _forMultiPart;
	private Object _forObject;
	private File _file;
	public HttpEntityConverter(Object obj)  {
		this(obj, null);
	}
	
	public HttpEntityConverter(Object obj, File file) {
		_forMultiPart = file != null;
		_forObject = obj;
		_file = file;
	}
	
	public String getMimeType() {
		if (_forObject instanceof Record) {
			if (((Record)_forObject).getMimeType() != null) {
				return ((Record)_forObject).getMimeType().getValue();
			}
		}
		
		return FileUtils.getMimeType(_file.getName());
		
	}
	
	private HttpEntity makeMultiPart() {
		
		MultipartEntityBuilder builder = MultipartEntityBuilder.create();
		builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

		
		Map<String,String> memberMap = ((TrimObject)_forObject).membersToMap();
		for (String key : memberMap.keySet()) {

			builder.addTextBody(key, memberMap.get(key));
		}
		
		if (_file != null) {
		//	FileBody fileBody = new FileBody(_file, ContentType.create(getMimeType()));
			
			builder.addBinaryBody("Files", _file, ContentType.create(this.getMimeType()), _file.getName()); //.addPart("Files", fileBody);
		}
		return builder.build();
	}
	
	public HttpEntity toEntity() {
		
		if (_forMultiPart == true) {
			return makeMultiPart();
		} else {
			TrimJson trimJson = new TrimJson();
			
			String json = trimJson.toJson(_forObject);
			return new StringEntity(json, ContentType.APPLICATION_JSON);
		}

	}
}
